<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>从服务器获取音频</title>
</head>
<body>
<button onclick="start()">播放</button>
<button onclick="stop()">停止</button>

<script>
    let source;

    const ctxClass = window.audioContext || window.AudioContext || window.AudioContext || window.webkitAudioContext;
    const ctx = new ctxClass();
    //自带蜂鸣声
    // const osc = ctx.createOscillator();
    // osc.connect(ctx.destination);

    //从服务器请求音频资源，在vue中可以直接import项目中的资源
    function request (url) {
        return new Promise (resolve => {
            let xhr = new XMLHttpRequest();
            xhr.open('GET', url);
            xhr.responseType = 'arraybuffer';
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    resolve(xhr.response);
                }
            };
            xhr.send();
        });
    }

    request("/11611.mp3").then(res => {
        console.log(res)
        ctx.decodeAudioData(res, decode => {
            source = ctx.createBufferSource();
            source.buffer = decode
            source.connect(ctx.destination);
        });
    });

    function start() {
        source.start(0)
    }

    function stop() {
        source.stop()
    }
</script>
</body>
</html>